#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, site 
import re, urllib
import datetime, time
import shutil
import sqlite3dbm

from generator import *
from paneo import *
from models import *

from paneo_html import PaneoImage

from sqlobject import *
sqlhub.processConnection = connectionForURI('sqlite://'+ARTICLES_DB)

import web

from mako.template import Template
from mako.lookup import TemplateLookup

TLOOKUP = TemplateLookup(   directories=[PANEO_SITE_DATA_DIR+'/_paneo_data/templates/include/',
                                         PANEO_SITE_DATA_DIR+'/forms/'],
                            input_encoding='utf-8',
                            output_encoding='utf-8',
                            encoding_errors='replace', 
                            default_filters=["none_to_blank", "unicode"],
                            #cache_impl='beaker',
                            #cache_args={
                            #},
                            imports = RENDER_IMPORTS )

def MakeHtmlForm( key , scfg , pages , formmail , bs , label):

    id = 'index'
    if formmail.get(key).get('pageid') != "":
        id = formmail.get(key).get('pageid')

    #TITLE
    bs.title.string = label + formmail[key].get('name') + u' | ' + scfg.get('SITENAME')

    t = unicode(bs)
    
    t = t.replace("<head>",'\r\n<head>')
    t = t.replace("</head>",'<%include file="_meta.html"/></head>')
    rep_head = '<!-- form css -->\n<link rel="stylesheet" href="//'+web.ctx.host+'/forms/formmail_' + key + '.css" media="all"/>\n</head>'
    t = t.replace("</head>",rep_head)
    t = t.replace("&lt;","<")
    t = t.replace("&gt;",">")
    t = t.replace("&amp;","&")

    #新着記事共通
    AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)

    template = Template(    
                            t,
                            lookup=TLOOKUP,
    )

    html = template.render(
                            web = web,
                            scfg = scfg, 
                            pages = pages,
                            id = id,
                            key = key,
                            formmail = formmail,
                            AT = AT,
                            ua_option = "",
                            bookmark = {},
    )

    return html

def emailcheck(email):
    msg = '^\w[\w\.\-\_]*[^\.]@\w[\w\-]*(\.[\w\-]{1,})+[^\.]$'
    regex = re.compile(msg)
    if regex.match(email):
        return True
    return False

class Entry:

    def __init__(self):
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self, key = "default" ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        formmail = dic.get('formmail')
        dic.close()

        #not found
        if not formmail.has_key(key):
            raise web.notfound()

        bs = None
        try:
            file = codecs.open(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key,"r","utf8")
            html = file.read()
            html = html.replace('<%include file="_meta.html"/>','')
            #bs = BeautifulSoup(html,"html5lib",fromEncoding="utf8")
            bs = BeautifulSoup(html,"html.parser",fromEncoding="utf8")
            file.close()
        except:
            return web.notfound()

        return MakeHtmlForm( key , scfg , pages , formmail , bs, label="" )

class Conf:

    def __init__(self):
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def POST( self, key = "default" ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        formmail = dic.get('formmail')
        dic.close()

        #not found
        if not formmail.has_key(key):
            raise web.notfound()

        i = web.input()

        try:
            file = codecs.open(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key,"r","utf8")
            html = file.read()
            html = html.replace('<%include file="_meta.html"/>','')
            #新着記事共通
            AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)
            template = Template(    
                                    html,
                                    lookup=TLOOKUP,
            )
            html = template.render(
                                    web = web,
                                    scfg = scfg, 
                                    pages = pages,
                                    id = id,
                                    key = key,
                                    formmail = formmail,
                                    AT = AT,
                                    ua_option = "",
                                    bookmark = {},
            )
            bs = BeautifulSoup(html,"html.parser",fromEncoding="utf8")
            file.close()
        except:
            return web.notfound()

        #TITLE
        bs.title.string = u'' + formmail[key].get('name') + u' | ' + scfg.get('SITENAME')

        check_field = {}
        check_val = {}
        #Required Check 
        required = False
        for fs in bs.find_all('fieldset'):
            paneo_form_name = fs.get('data-paneo-form')
            paneo_form_required = fs.get('data-paneo-form-required')
            val = ""
            if i.has_key( paneo_form_name ):
                val = i.get( paneo_form_name )
            
            if paneo_form_required == "True" and val == "":
                check_field[paneo_form_name] = "ERROR"
                required = True
                if fs.has_key("class"):
                    fs["class"] = fs["class"] + " alert"
                else:
                    fs["class"] = "alert"

            #Email
            if paneo_form_name == "email" and not emailcheck( val ):
                check_field[paneo_form_name] = "ERROR"
                required = True
                if fs.has_key("class"):
                    fs["class"] = fs["class"] + " alert"
                else:
                    fs["class"] = "alert"

            #Email compaire
            if paneo_form_name == "email":
                eck = fs.find_all('input',{'name':'email_cmp'})
                if eck:
                    if val != i.get("email_cmp"):
                        check_field[paneo_form_name] = "ERROR"
                        required = True
                        if fs.has_key("class"):
                            fs["class"] = fs["class"] + " alert"
                        else:
                            fs["class"] = "alert"

            #value set
            for fl in fs.find_all(['input','textarea','select']):
                tp = fl.get("type") 
                if tp == "text" or tp == "email" or tp == "url":
                    fl["value"] = i.get(fl['name']) 
                if tp == "radio" :
                    for c in fl.parent.find_all('input'):
                        if c["value"] == i.get(fl['name']):
                            c["checked"] = "checked"
                        else:
                            del c["checked"]
                if tp == "checkbox":
                    if i.has_key(fl['name']):
                        ii = eval("web.input(%s = [])" % fl['name'])
                        for v in ii.get(fl['name']):
                            if fl["value"] == v:
                                fl["checked"] = "checked"
                        check_val[paneo_form_name] = ii.get(fl['name'])

                if fl.name == "select":
                    for o in fl.find_all("option"):
                        if o["value"] == i.get(fl['name']):
                            o["selected"] = "selected"
                        else:
                            del o["selected"]
                if fl.name == "textarea":
                    fl.string = i.get(fl['name']) 
                if tp is None:
                    pass

        if required :
            frm = bs.find_all('form')
            if frm is not None:
                frm = frm[0]
                soup = BeautifulSoup(u'<div class="formalert">必須入力をご確認ください。</div>') 
                frm.insert_before(soup.div)
            return MakeHtmlForm( key , scfg , pages , formmail , bs , label=u"[必須項目確認] " )


        for fs in bs.find_all('fieldset'):
            paneo_form_name = fs.get('data-paneo-form')
            paneo_form_required = fs.get('data-paneo-form-required')

            val = ""
            if i.has_key( paneo_form_name ):
                val = i.get( paneo_form_name )
                if check_val.has_key( paneo_form_name ) :
                    val = check_val[paneo_form_name]
                if type(val) == type([]):
                    s = val
                    val = ""
                    for v in s:
                        val = val + v + "\r\n"

            fs.clear()
            soup = BeautifulSoup('<input type="hidden" name="%s" value="%s"/>' % (paneo_form_name,val)) 
            fs.append(soup.input)
            soup = BeautifulSoup('<div class="formvalue">%s</div>' % (val.replace('\r\n','<br>'))) 
            fs.append(soup.div)

        fs = bs.select("fieldset.send")
        if fs is not None:
            fs = fs[0]
            soup = BeautifulSoup(u'<button class="submit" name="CMD_SEND" type="submit">送 信</button>')
            fs.append(soup.button)
            soup = BeautifulSoup(u'<button class="cancel" name="BACK" onclick="history.go(-1);return false;" >修正</button>')
            fs.append(soup.button)

        fs = bs.find_all('form')
        if fs is not None:
            fs = fs[0]
            fs['action'] = '/forms/formmail_%s_thax.html' % key

        #t = unicode(bs)
        #
        #t = t.replace("<head>",'\r\n<head>')
        #t = t.replace("</head>",'<%include file="_meta.html"/></head>')
        #t = t.replace("&lt;","<")
        #t = t.replace("&gt;",">")
        #t = t.replace("&amp;","&")

        #template = Template(    
        #                        t,
        #                        lookup=tlookup,
        #)

        #id = 'index'
        #if formmail.get(key).get('pageid') != "":
        #    id = formmail.get(key).get('pageid')

        #html = template.render(
        #                        id = id,
        #                        key = key,
        #                        web = web,
        #                        scfg = scfg, 
        #                        pages = pages,
        #                        formmail = formmail,
        #                        ua_option = "",
        #)

        #return html
        return MakeHtmlForm( key , scfg , pages , formmail , bs , label=u"[送信確認] " )

import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate

##### SEND MAIL ######
def create_message( key , subject , from_addr , to_addr ):
    return msg


class Thanx:

    def __init__(self):
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def POST( self, key = "default" ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        formmail = dic.get('formmail')
        dic.close()

        #not found
        if not formmail.has_key(key):
            raise web.notfound()

        i = web.input()

        FORM_MSG = ""
        #MAKE FORM MSG
        #try:
        if True:
            file = codecs.open(PANEO_SITE_DATA_DIR+'forms/formmail_%s_ent.html' % key,"r","utf8")
            html = file.read()
            html = html.replace('<%include file="_meta.html"/>','')
            #新着記事共通
            AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)
            template = Template(    
                                    html,
                                    lookup=TLOOKUP,
            )
            html = template.render(
                                    web = web,
                                    scfg = scfg, 
                                    pages = pages,
                                    key = key,
                                    formmail = formmail,
                                    AT = AT,
                                    ua_option = "",
                                    bookmark = {},
            )
            bs = BeautifulSoup(html,"html.parser",fromEncoding="utf8")
            file.close()
        #except:
        #    return web.notfound()

        fieldset = bs.find_all('fieldset')

        for fs in fieldset:
            paneo_form_name = fs.get('data-paneo-form')
            paneo_form_required = fs.get('data-paneo-form-required')
            
            val = ""
            if i.has_key( paneo_form_name ):
                val = i.get( paneo_form_name )
                label = bs.find_all("label",{"for":paneo_form_name})
                if len(label) != 0:
                    label = label[0]
                    #label = label.string
                    label_txt = "".join([unicode(t) for t in label.contents])
                    label_txt = label_txt.replace("<br/>"," ")
                    FORM_MSG = FORM_MSG + ( u"[%s]\r\n%s\r\n\r\n" % ( label_txt, val ))

        #THAX FORM
        #try:
        if True:
            file = codecs.open(PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key,"r","utf8")
            html = file.read()
            #html = html.replace('<%include file="_meta.html"/>','')
            ##新着記事共通
            #AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)
            #template = Template(    
            #                        html,
            #                        lookup=TLOOKUP,
            #)
            #html = template.render(
            #                        web = web,
            #                        scfg = scfg, 
            #                        pages = pages,
            #                        key = key,
            #                        formmail = formmail,
            #                        AT = AT,
            #                        ua_option = "",
            #                        send_msg = send_msg,
            #                        bookmark = {},
            #)
            bs = BeautifulSoup(html,"html.parser",fromEncoding="utf8")
            file.close()
        #except:
        #    return web.notfound()

        t = unicode(bs)
        
        t = t.replace("<head>",'\r\n<head>')
        t = t.replace("</head>",'<%include file="_meta.html"/></head>')
        t = t.replace("&lt;","<")
        t = t.replace("&gt;",">")
        t = t.replace("&amp;","&")

        template = Template(    
                                t,
                                lookup=TLOOKUP,
        )

        id = 'index'
        if formmail.get(key).get('pageid') != "":
            id = formmail.get(key).get('pageid')

        fm = formmail.get(key)

        #SEND MAIL
        google_account = fm.get("account") 
        google_pass = fm.get("password") 
        if fm.get("mailfrom") == "":
            from_addr = fm.get("mailfrom") 
        else:
            from_addr = fm.get("account")
        if i.has_key("email"):
            to_addr = i.get("email") 
        else:
            to_addr = from_address 
        subject = fm.get("subject") 

        encoding = "ISO-2022-JP"
        msg_temp = Template(    filename=PANEO_SITE_DATA_DIR+'forms/formmail_%s_msg.html' % key, 
                                output_encoding='utf-8',
                                input_encoding='utf-8',
                                encoding_errors='replace',
                                lookup=TLOOKUP,
                                )
        #新着記事共通
        AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)

        body = msg_temp.render( 
                                TITLE = fm.get("name"),     
                                FORM_MSG = FORM_MSG,
                                AT = AT,
                                bookmark = {},
                                i = i,
                            )

        try:
            msg = MIMEText(body.encode(encoding), 'Plain', encoding)
        except:
            msg = MIMEText(body, 'Plain', 'utf-8')

        msg['Subject'] = Header(subject, encoding)
        msg['From'] = from_addr
        msg['To'] = to_addr
        #msg['Bcc'] = from_addr
        msg['Date'] = formatdate()

        try:
            s = smtplib.SMTP('smtp.gmail.com', 587)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login( google_account, google_pass )
            s.sendmail( google_account , [to_addr,google_account], msg.as_string())
            s.close()
        except:
            return web.seeother('http://' + web.ctx.host + '/forms/formmail_%s_err.html' % key)

        send_msg = u"送信完了"

        #新着記事共通
        AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)
        
        html = template.render(
                                id = id,
                                key = key,
                                web = web,
                                scfg = scfg, 
                                pages = pages,
                                formmail = formmail,
                                AT = AT,
                                ua_option = "",
                                send_msg = send_msg,
                                bookmark = {},
                                i = i,
        )

        return html

class Err:

    def __init__(self):
        web.header("Content-Type", "text/html; charset=UTF-8")
        web.header("Cache-Control", "no-cache, must-revalidate")
        web.header("Pragma", "no-cache")

    def GET( self, key = "default" ):

        dic = sqlite3dbm.sshelve.open(PANEO_DB)
        scfg = dic.get('siteconfig')
        pages = dic.get('pages')
        formmail = dic.get('formmail')
        dic.close()

        #not found
        if not formmail.has_key(key):
            raise web.notfound()

        try:
            file = codecs.open(PANEO_SITE_DATA_DIR+'forms/formmail_%s_thx.html' % key,"r","utf8")
            html = file.read()
            html = html.replace('<%include file="_meta.html"/>','')
            bs = BeautifulSoup(html,"html.parser",fromEncoding="utf8")
            file.close()
        except:
            return web.notfound()

        #TITLE
        bs.title.string = u"[送信エラー] " + formmail[key].get('name') + u' | ' + scfg.get('SITENAME')

        t = unicode(bs)
        
        t = t.replace("<head>",'\r\n<head>')
        t = t.replace("</head>",'<%include file="_meta.html"/></head>')
        t = t.replace("&lt;","<")
        t = t.replace("&gt;",">")
        t = t.replace("&amp;","&")

        template = Template(    
                                t,
                                lookup=TLOOKUP,
        )

        id = 'index'
        if formmail.get(key).get('pageid') != "":
            id = formmail.get(key).get('pageid')

        fm = formmail.get(key)
        if fm.get("mailfrom") == "":
            from_addr = fm.get("mailfrom") 
        else:
            from_addr = fm.get("account")

        send_msg = u"""<div class="formalert">送信エラーが発生しました</div>
        <p>
        フォームから正常に送信できませんでした。<br>
        <br>
        大変お手数をおかけいたしますが、<br>
        [<a href="mailto:%s">%s</a>]までメールにてご連絡ください。
        </p>
""" % ( from_addr, from_addr )

        #新着記事共通
        AT = ArticlesType.select(ArticlesType.q.id == '1').getOne(default=None)

        html = template.render(
                                id = id,
                                key = key,
                                web = web,
                                scfg = scfg, 
                                pages = pages,
                                formmail = formmail,
                                ua_option = "",
                                AT = AT,
                                send_msg = send_msg,
                                bookmark = {},
        )

        return html
